<template>
  <a-drawer
    :title="title"
    headerStyle="background-color: #FF943E"
    :maskStyle="{background: 'transparent'}"
    :maskClosable="false"
    :visible="dialog"
    width="500"
    @close="cancel"
  >
    <input type="text" v-model="title" class="change_btn"/>
    <div class="worksheet_trigger_body">
      <div class="worksheet_trigger_form">
        <div class="form_item" v-for="item in schemaInputs" :key="item.id">
          <template v-if="item.customType === 'notice'">
            <div class="form_item_title">{{item.title}}</div>
             <workflow-notice v-model="inputs[item.key]" :noticeData="inputs.noticeStoreData" @change="handleNoticeChange" :output="output"></workflow-notice>
          </template>
          <template v-if="item.customType === 'userIds'">
            <div class="form_item_title">指定人员</div>
            <user-container v-for="item in userList" :user="item" :output="output" :key="item.userId" @deleteuser="handleDeleteUser"></user-container>
            <a-popover trigger="click" overlayClassName="user_add_popover" placement="bottomLeft">
              <div slot="content" class="user_add_content">
                <div class="user_add_list" @click="handleAddUser">从用户列表中添加</div>
                <div class="user_add_desc">使用流程节点对象下的人员</div>
                <a-collapse accordion expand-icon-position="right">
                  <a-collapse-panel v-for="item in outputUsers" :key="item.nodeId" :header="item.nodeName">
                    <div class="popover_container_item" @click.stop="handleItemUserClick(item, fieldItem)" v-for="fieldItem in item.outputs" :key="fieldItem.name">
                      {{fieldItem.alia}}
                    </div>
                  </a-collapse-panel>
                </a-collapse>
              </div>
              <a-button>添加成员</a-button>
            </a-popover>
          </template>
          <template v-if="item.customType === 'selectNode'">
            <div class="form_item_title">{{item.title}}</div>
            <a-select v-model="inputs[item.key]" optionFilterProp='children' show-search style="width: 100%">
              <a-select-option v-for="item in output" :key="item.nodeId" :value="item.nodeId">
                {{item.nodeName}}
              </a-select-option>
            </a-select>
          </template>
          <!-- <template v-if="item.customType === 'approveType'">
            <div class="form_item_title">{{item.title}}</div>
            <a-select v-model="inputs.approveType" style="width: 100%">
                <a-select-option :value="0">
                    或签（一名审批人通过或否决即可）
                </a-select-option>
                <a-select-option :value="1">
                    会签（需所有审批人通过）
                </a-select-option>
                <a-select-option :value="2">
                    会签（只需一名审批人通过，否决需全员否决）
                </a-select-option>
            </a-select>
          </template>
          <template v-if="item.customType === 'approveSettings'">
            <div class="form_item_title">{{item.title}}</div>
            <div>
                <a-checkbox>
                    允许审批人转审
                </a-checkbox>
            </div>
            <div>
                <a-checkbox>
                    允许审批人加签
                </a-checkbox>
            </div>
            <div>
                <a-checkbox>
                    否决后，允许退回
                </a-checkbox>
            </div>
            <div>
                <a-checkbox>
                    通过后，必须签名
                </a-checkbox>
            </div>
          </template>
          <template v-if="item.customType === 'btnName'">
            <div class="form_item_title">{{item.title}}</div>
            <div>
                <span>通过按钮</span>
                <a-input></a-input>
            </div>
            <div>
                <span>否决按钮</span>
                <a-input></a-input>
            </div>
          </template> -->
        </div>
      </div>
      <div class="worksheet_trigger_foot">
        <a-button type="primary" @click="save">
          保存
        </a-button>
        <a-button @click="cancel">
          取消
        </a-button>
      </div>
    </div>
    <user-modal v-if="showUserModal" :userData="userData" :visible="showUserModal" @ok="addUser" @close="showUserModal = false"></user-modal>
  </a-drawer>
</template>
<script>
import { getUserList } from '@/api/authority'
import { DataType } from '@/filterConstant'
import {uuid} from "@/utils/utils"
import {getNodeOutput} from "@/api/appWorkflow"
import WorkflowNotice from "../../workflowNotice.vue"
import UserModal from '../../../../modal/userModal.vue'
import UserContainer from '../../user/index.vue'
export default {
  components: {
    UserModal,
    UserContainer,
    WorkflowNotice,
  },
  props: {
    dialog: {
      type: Boolean,
      default: false
    },
    node: {
      type: Object,
      default: undefined
    }
  },
  data(){
      return {
        schemaInputs: [],
        inputs:{},
        showUserModal: false,
        output: [],
        userList: [],
        userData: [],
        title: ''
      }
  },
  watch: {
    dialog: {
      async handler (val) {
        if(this.dialog){
          this.title = this.node?.name || '审批'
          let schemaInputs = this.node?.schema?.inputs || {}
          this.inputs = this.node?.inputs || {}
          let output = await getNodeOutput({
            automationId: this.id,
            nodeId: this.node.nodeId
          })
          this.output = output
          
         if(this.inputs?.userIds){
            let userIds = this.inputs.userIds
            let userList = []
            
            let re = /^{{(\w+(?:\.\w+)+)}}$/
            getUserList().then((res) => {
                if(res.data && res.data.success){
                    userIds.forEach(u => {
                        if(re.test(u)){
                          let split = re.exec(u)[1].split('.')
                          
                          let outputItem = output.find(o => o.nodeId === split[0])
                          let fieldItem = {}
                          let flag = false
                          if(outputItem){
                            fieldItem = outputItem.outputs.find(o => o.name === split[3])
                            flag = !!fieldItem
                          }
                          if(flag){
                            userList.push({
                              userId: uuid(),
                              type: 'formNode',
                              outputItem,
                              fieldItem,
                            })
                          }
                        }else {
                          for (let i = 0; i < res.data.data.length; i++) {
                              let user = res.data.data[i];
                              if(u === user.userId){
                                  userList.push({
                                      userId: user.userId,
                                      userAlia: user.name,
                                      type: 'formUserList',
                                  })
                                  break
                              }
                          }
                        }
                    })
                }
                this.userList = userList
            })
          }
          
          this.schemaInputs = schemaInputs.order.map(o => {
            for (const key in schemaInputs.properties) {
              if(key === o){
                return {
                  ...schemaInputs.properties[key],
                  id: uuid(),
                  key
                }
              }
            }
          })
        }
      },
      deep: true,
    },
  },
  methods: {
    handleNoticeChange(value){
      this.inputs.noticeStoreData = value
    },
    handleAddUser(){
      this.userData = []
      this.showUserModal = true
      getUserList().then((res) => {
          if(res.data && res.data.success){
              let userData = [];
              for (let i = 0; i < res.data.data.length; i++) {
                  let user = res.data.data[i];
                  let flag = false
                  for(let j = 0; j < this.userList.length; j++){
                    let addU = this.userList[j]
                    if(addU.userId === user.userId){
                      flag = true
                      break
                    }
                  }
                  if(flag) continue
                  userData.push({
                      userId: user.userId,
                      userAlia: user.name,
                      type: 'formUserList',
                      check: false
                  })
              }
              this.userData = userData
          }
      })
    },
    handleItemUserClick (outputItem, fieldItem) {
      this.userList.push({
        userId: uuid(),
        type: 'formNode',
        outputItem,
        fieldItem,
      })
    },
    handleDeleteUser (userId) {
      this.userList = this.userList.filter(u => u.userId !== userId)
    },
    cancel () {
      this.$emit('close')
    },
    addUser (userList) {
      this.userList = [...this.userList, ...userList]
    },
    async save(){
        let userIds = []
        this.userList.forEach(u => {
          if(u.type === 'formUserList'){
            userIds.push(u.userId)
          }
          else if(u.type === 'formNode'){
            userIds.push(`{{${u.outputItem.nodeId}.outputs.${u.fieldItem.parentKey}.${u.fieldItem.name}}}`)
          }
        })
        this.inputs.userIds = userIds
        this.$emit('close')
        this.$emit('setProperties', {
            inputs: this.inputs
        }, this.title)
    },
  },
  computed:{
    appId(){
      return this.$route.params.appId
    },
    id(){
        return this.$route.params.id
    },
    outputUsers(){
      let ouput = this.output
      let newOupput = []
      ouput.forEach( o => {
        if(o.outputs){
          let newo = JSON.parse(JSON.stringify(o))
          let outputs = o.outputs.filter(p => p.dataType === DataType.USER_SELECT || p.dataType === DataType.PERSONNEL || p.dataType === DataType.MEMBER )
          newOupput.push(Object.assign(newo, {
            outputs
          }))
        }
      })
      return newOupput
    }
  }
}
</script>

<style lang="less">
.form_item{
  margin-top: 10px;
  margin-bottom: 20px;
}
.form_item_title{
  /* font-size: 18px; */
  /* font-weight: bold; */
  color: #000000;
  margin: 15px 0 5px 0;
}

.user_add_popover{
  .ant-popover-inner-content{
    padding: 0;

    .user_add_list{
      padding: 10px 16px;
      cursor: pointer;
      background-color: #fafafa;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
    }
    .user_add_content{
      width: 400px;
      max-height: 400px;
      overflow: hidden;
      overflow-y: auto;

      .user_add_desc{
        padding: 0 10px;
        margin-top: 10px;
      }
      .popover_container_item{
        height: 35px;
        line-height: 35px;
        padding: 0 10px;
        cursor: pointer;
      }
      .popover_container_item:hover{
        background-color: rgba(72, 161, 255, 0.8);
        color: white;
      }
    }

  }
}
.change_btn{
  position: absolute;
  top: 10px;
  left: 15px;
  border: none;
  height: 35px;
  width: 400px;
  font-size: 17px;
  padding-left: 10px;
  background-color: #FF943E;
}
.change_btn:hover{
  background-color: #f5aa6d;
}
.change_btn:focus{
  background-color: white;
}
</style>